<?php


namespace App\Http\Service;


use App\Models\SchoolCollectModel;
use App\Models\userModel;
use Illuminate\Support\Facades\DB;

class UserService
{
    public function addInfo($data){
        $list = [];
        //微信公众号登录
        if(array_key_exists("token",$data)) {
            //获取用户微信id
            $list['openid'] = $data['openid'];
            $token = $data['token'];
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token . '&openid=' . $list['openid'];
//            $url = 'https://api.weixin.qq.com/sns/userinfo';
//            $params = ['access_token'=>$token ,'&openid'=> $list['openid']];

            $json = self::doGet($url);
            $result = json_decode($json);
            $list = array(
                'openid' => $data['openid'],
                'real_name' => $result->nickname,
                'sex' => $result->sex,
                'avatar_img' => $result->headimgurl,
            );
        }
        //进行判断openID是否存在
        $user_info = (new userModel())->searchDataType($data['openid']);
//        x($user_info);
        if (!empty($user_info)){
            $list['uid'] =  $user_info->uid;
            return $list;
        }
        $list['uid'] =  (new userModel())->addInfo($list);
        return $list;
    }
    /**
     * 发起请求
     * @param $url
     * @param int $timeout
     * @return mixed
     */
    public static function doGet($url, $timeout = 5)
    {
        //启动一个CURL会话
        $ch = curl_init();
        // 设置curl允许执行的最长秒数
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        // 获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        // 执行操作
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     * 获取所有教职的数据
     * @param $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getList($data){
        $data['limit'] =  $data['limit'] ?? 10;
        $data['page'] = $data['page'] ?? 1;
        $model =   DB::table("school_collect");
//        $model = (new SchoolCollectModel())->getLastQuery();
        if(!empty($data['school_title'])){
            $model->where('school_title','like',"%".$data['school_title']."%");
        }
        if(!empty($data['not_finish_tel'])){
            $model->where('not_finish_tel','=',$data['not_finish_tel']);
        }
        $model->orderBy('id','desc');
        return   $model->paginate($data['limit'],'*','page',$data['page']);

    }
}